package test;

import java.io.IOException;

public class CPU占用率为50 {

    public static void main(String[] args) throws InterruptedException, IOException {

        setCpuAffinity(0);

        int busyTime = 10;
        int idleTime = 10;

        while (true) {
            long startTime = System.currentTimeMillis();
            //busy loop:
            while ((System.currentTimeMillis() - startTime) <= busyTime) ;
            Thread.sleep(idleTime);
        }
    }

    // 设置进程的 CPU 亲和性，只使用指定的 CPU 核心
    private static void setCpuAffinity(int cpuCore) throws IOException {
        String command = "cmd /c start /affinity " + (1 << cpuCore) + " java";
        ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
        processBuilder.start();
    }
}
